package com.tian.hello.ipc.server;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import androidx.annotation.Nullable;
import android.util.Log;

import com.tian.hello.ipc.Book;
import com.tian.hello.ipc.BookManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: 远程服务
 * <br/>Author:  tianjinyong
 * <br/>Date:    2020/7/15 3:57 PM
 */
public class AIDLService extends Service {

    private final String TAG = this.getClass().getSimpleName();

    private List<Book> mBooks = new ArrayList<>();

    private final BookManager.Stub mBookManager = new BookManager.Stub() {
        @Override
        public List<Book> getBooks() throws RemoteException {
            synchronized (this) {
                Log.e(TAG, Thread.currentThread().getName()+" invoking getBooks() method , now the list is : " + mBooks.toString());
                return mBooks;
            }
        }

        @Override
        public void addBook(Book book) throws RemoteException {
            synchronized (this) {
                if(book == null)
                    return;
                book.setPrice(2244);
                if(!mBooks.contains(book)) {
                    mBooks.add(book);
                }
                try {
                    Thread.sleep(25 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //打印mBooks列表，观察客户端传过来的值
                Log.e(TAG, Thread.currentThread().getName()+ " invoking addBooks() method , now the list is : " + mBooks.toString());
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        Book book = new Book();
        book.setName("Android开发艺术探索");
        book.setPrice(28);
        mBooks.add(book);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(getClass().getSimpleName(), String.format("on bind,intent = %s", intent.toString()));
        return mBookManager;
    }
}
